import subprocess
import re
import threading
from flask import Flask, render_template, request, jsonify

app = Flask(__name__)

# 引擎路径（根据你的系统修改）
ENGINE_PATH = "./engine/pikafish"

# 全局引擎进程管理
engine_lock = threading.Lock()
engine_process = None

def start_engine():
    """启动象棋引擎进程"""
    global engine_process
    if engine_process is None:
        engine_process = subprocess.Popen(
            ENGINE_PATH,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            universal_newlines=True,
            bufsize=1
        )
        # 初始化引擎
        engine_process.stdin.write("uci\n")
        engine_process.stdin.write("isready\n")
        engine_process.stdin.flush()
        # 读取响应直到准备好
        while True:
            line = engine_process.stdout.readline().strip()
            if line == "readyok":
                break

def send_command(command):
    """向引擎发送命令并获取响应"""
    with engine_lock:
        print
        engine_process.stdin.write(command + "\n")
        engine_process.stdin.flush()
        if command.startswith("position"):
            return ""
        output = []
        while True:
            line = engine_process.stdout.readline().strip()
            if line.startswith("bestmove") or line == "readyok":
                output.append(line)
                break
            if line and not line.startswith("info"):
                output.append(line)
        return output

def get_ai_move(fen, difficulty=2):
    """获取AI的移动"""
    start_engine()
    
    # 设置难度（思考深度）
    depth = 8 + difficulty * 4
    
    # 设置棋盘位置
    send_command(f"position fen {fen}")
    
    # 请求AI移动
    response = send_command(f"go depth {depth}")
    
    # 解析最佳移动
    for line in response:
        if line.startswith("bestmove"):
            match = re.search(r"bestmove (\w+)", line)
            if match:
                return match.group(1)
    return None

@app.route('/')
def index():
    """渲染主页面"""
    return render_template('index.html')

@app.route('/get_move', methods=['POST'])
def get_ai_move_api():
    """API端点：获取AI移动"""
    data = request.json
    fen = data.get('fen')
    difficulty = data.get('difficulty', 2)
    
    if not fen:
        return jsonify({"error": "Missing FEN string"}), 400
    
    move = get_ai_move(fen, difficulty)
    if move:
        return jsonify({"move": move})
    return jsonify({"error": "Failed to get AI move"}), 500

@app.route('/reset_engine', methods=['POST'])
def reset_engine():
    """重置引擎（用于新游戏）"""
    global engine_process
    if engine_process:
        engine_process.terminate()
        engine_process = None
    return jsonify({"status": "success"})

if __name__ == '__main__':
    # 启动时初始化引擎
    start_engine()
    app.run(host='0.0.0.0', port=5000, debug=True)
